﻿module Sustainalytics.Portfolio {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    // Portfolio List controller
    export class PortfolioListController {

        // portfolio filter
        public portfolioFilter: PortfolioFilterDto=new PortfolioFilterDto();
        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of portfolios
        public portfolioList: PortfolioDto[];
        // total number of portfolios
        public portfolioCount: number;
        private accountId: string;
        private userId: string;
        public hasPortfolioPermision: boolean;
        public isSeeMore: boolean;

        private scopeDestroyed: boolean;

        public sharedSelected: boolean;

        public systemSelected: boolean;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private PortfolioService: PortfolioService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            private $modal: Common.IModal) {

            var ctx = this;

            $scope['portfolioList'] = ctx;

            ctx.scopeDestroyed = false;
            ctx.hasPortfolioPermision = this.PortfolioService.hasPermision();

            ctx.portfolioFilter.isMyPortfolio = true;
            ctx.portfolioFilter.namePortfolio = "";
            ctx.portfolioFilter.isNameEqual = false;
            ctx.portfolioFilter.portfolioType = PortfolioTypes.Custom;
            ctx.portfolioFilter.sharingStatus = PortfolioSharingStatus.All;
            ctx.orderByCol = "NameLowercase";
            ctx.orderByAsc = true;

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.handlePagerChanged();
            ctx.handleScopeDestroyed();
        }

        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function() {
                ctx.scopeDestroyed = true;
            });
        }

        // search for portfolios when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function(ev, pager: Pager.PagerController) {
                ctx.searchPortfolio();
            });
        }

        // order list of portfolios
        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            } else {
                ctx.orderByCol = col;
                ctx.orderByAsc = true;
            }
            ctx.searchPortfolio();
        }

        // search list of portfolios
        public searchPortfolio(): ng.IPromise<{}> {
            var ctx = this;
            ctx.$rootScope['loading'] = true;


            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();

            // get portfolio items
            var promiseGet: ng.IPromise<PortfolioListDto> = ctx.PortfolioService.getPortfolios(ctx.portfolioFilter, skip, take, [ctx.orderByCol], ctx.orderByAsc, ctx.accountId, ctx.userId);

            var portfolioListTemp: PortfolioDto[];
            var portfolioCountTemp: number;
            //on success list portfolios
            promiseGet.then(lst => {

                portfolioListTemp = lst["portfolios"];
                portfolioCountTemp = lst["count"];
            });

            //get portfolios count


            // after get and count are resolved set controller properties
            var promiseAll = ctx.$q.all([promiseGet]);

            promiseAll
                .then(() => {
                    this.portfolioList = portfolioListTemp;
                    this.portfolioCount = portfolioCountTemp;
                    pager.setTotalItemsCount(portfolioCountTemp);
                })
               .finally(() => {
                    this.$rootScope['loading'] = false;
                });

            return promiseAll;
        }

        // search for my portfolio
        public selectMyPortfolio() {
            var ctx = this;

            if (ctx.scopeDestroyed)
                return;

            var filter = new PortfolioFilterDto();
            filter.namePortfolio = "";
            filter.isMyPortfolio = true;
            filter.sharingStatus = PortfolioSharingStatus.All;
            filter.portfolioType = PortfolioTypes.Custom;
            filter.isNameEqual = false;

            ctx.portfolioFilter = filter;
            this.sharedSelected = false;
            this.systemSelected = false;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        // search for shared portfolio
        public selectSharedPortfolio() {
            var ctx = this;

            if (ctx.scopeDestroyed)
                return;

            var filter = new PortfolioFilterDto();
            filter.namePortfolio = "";
            filter.sharingStatus = PortfolioSharingStatus.Shared;
            filter.portfolioType = PortfolioTypes.Custom;
            filter.isMyPortfolio = false;
            filter.isNameEqual = false;
            filter.isSystemPortfolio = false;
            ctx.portfolioFilter = filter;

            this.sharedSelected = true;
            this.systemSelected = false;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        public selectSystemPortfolio() {

            var ctx = this;

            if (ctx.scopeDestroyed)
                return;

            var filter = new PortfolioFilterDto();
            filter.namePortfolio = "";
            filter.isMyPortfolio = true;
            filter.isNameEqual = false;
            filter.isSystemPortfolio = true;
            filter.sharingStatus = PortfolioSharingStatus.All;
            filter.portfolioType = PortfolioTypes.System;
            ctx.portfolioFilter = filter;

            this.systemSelected = true;
            this.sharedSelected = false;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        public deletePortfolio(id): ng.IPromise<{}> {
            var ctx = this;

            if (confirm("Are you sure you want to delete the selected Portfolio?")) {

                var promiseDelete = ctx.PortfolioService.deletePortfolio(id);

                promiseDelete.finally(() => {
                    // repopulate list
                    this.searchPortfolio();
                });

                return promiseDelete;
            }
        }

        public setShared(item: PortfolioDto) {
            var ctx = this;

            var portfolioSharing = new PortfolioSharingDto();
            portfolioSharing.id = item.id;
            portfolioSharing.sharingStatus = PortfolioSharingStatus.Shared;

            var modalInstanceSubscribe = ctx.$modal.open({
                templateUrl: 'Views/Portfolio/portfolioExists_dialog.tpl.html',
                controller: 'PortfolioCheckController',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    message: function() {
                        return "Are you sure you want to share the portfolio?";
                    },
                    informationMessage: function() {
                    }
                }
            });

            modalInstanceSubscribe.result.then((out) => {
                if (out["portfolioCheck"] === true) {
                    var promiseUpdate = ctx.PortfolioService.updateStatusPortfolio(portfolioSharing);

                    promiseUpdate.finally(() => {
                        item.sharingStatus = PortfolioSharingStatus.Shared;
                        ctx.searchPortfolio();
                    });
                }
            });
        }

        public setPrivate(item: PortfolioDto) {
            var ctx = this;

            var portfolioSharing = new PortfolioSharingDto();
            portfolioSharing.id = item.id;
            portfolioSharing.sharingStatus = PortfolioSharingStatus.Private;

            var modalInstanceSubscribe = ctx.$modal.open({
                templateUrl: 'Views/Portfolio/portfolioExists_dialog.tpl.html',
                controller: 'PortfolioCheckController',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    message: function() {
                        return "Are you sure you want to unshare the portfolio?";
                    },
                    informationMessage() {
                        if (item.hasSubscription) {
                            return "A user of the account has activated the alert service for this portfolio!";
                        } else {
                            return "";
                        }
                    }
                }
            });

            modalInstanceSubscribe.result.then((out) => {
                if (out['portfolioCheck'] == true) {
                    var promiseUpdate = ctx.PortfolioService.updateStatusPortfolio(portfolioSharing);

                    promiseUpdate.finally(() => {
                        item.sharingStatus = 1;
                        ctx.searchPortfolio();
                    });
                }
            });
        }

        public addTaskExportPortfolio(item: PortfolioDto): void {
            var ctx = this;

            var data = {
                id: item.id,
                accountId: ctx.accountId,
                userId: ctx.userId,
                name: item.name
            }

            ctx.LongRunningTaskManagerService.runTask('Portfolio_' + item.name + "_" + moment().format("DDMMYYYY"), angular.toJson(data), LRTM.LongRunningTaskTypeEnum.PortfolioExportExcel, true, null);

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId,
                'cookieDomain': 'none',
                'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId,
                PortfolioId: item.id
            };

            ga('globalAccess.send', {
                'hitType': 'event',
                'eventCategory': 'Portfolio Management',
                'eventAction': 'ExcelPortfolioExport',
                'eventLabel': JSON.stringify(gaObject)
            });


        }

        openAddPortfolioPopup() {
            var ctx = this;
            var modalInstance;

            if (!(ctx.systemSelected || (ctx.portfolioFilter.isSystemPortfolio && ctx.portfolioFilter.isMyPortfolio))) {

                modalInstance = ctx.$modal.open(
                {
                    templateUrl: '/Views/Portfolio/addPortfolioWithSecurities.tpl.html',
                    controller: 'PortfolioUploadController',
                    size: 'lg',
                    backdrop: false,
                    resolve: {
                        listPortfoliosHandler: () => ctx.searchPortfolio.bind(ctx)
                    }
                    });


                modalInstance.result.then((out) => {
                    if (out["newStatus"] === 3)
                        ctx.searchPortfolio();
                });
            } else {
                modalInstance = ctx.$modal.open(
                {
                    templateUrl: "/Views/Portfolio/addEditSystemPortfolio.tpl.html",
                    controller: "SystemPortfolioController",
                    size: "lg",
                    backdrop: false,
                    resolve: {
                        portfolio() {
                            return new PortfolioDto();
                        }
                    }
                    });
                modalInstance.result.then((out) => {
                    if (out["portfolioStatus"] === true)
                        ctx.searchPortfolio();
                });
            }

           
        }

        //#region Tutorial
        public seeMoreText() {
            var ctx = this;
            ctx.isSeeMore = true;
        }

        public seeLessText() {
            var ctx = this;
            ctx.isSeeMore = false;
        }

        public openVideoPopup() {
            var ctx = this;

            var $modalInstance = ctx.$modal.open(
            {
                templateUrl: '../../../Views/tutorial_dialog.tpl.html',
                controller: 'TutorialController',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    title: function() {
                        return "Portfolio Management and Monitoring";
                    },
                    url: function() {
                        return "http://www.sustainalytics.com/sites/default/files/uploads/2015-08-25-GAV3-PortfolioManagement.mp4";
                    }

                }

            });
        }

        //#endregion
    }


    // register controller with News Angular module
    angular.module(portfolioModuleName).controller('PortfolioListController',
    ['$rootScope', '$scope', '$q', '$location', 'PortfolioService', 'notificationFactory', 'staticObjects', 'LongRunningTaskManagerService', '$modal', PortfolioListController]);
}